package com.xyh.concurrency.example.FockJoin;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

@Slf4j
public class FockJoinDemo extends RecursiveTask<Integer> {
    public static final int threshold = 2;
    private int start;
    private int end;

    public FockJoinDemo(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        //判断是否达到了计算的阀值
        boolean canCompute = (end - start) <= threshold;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
        } else {
            //任务大于阀值就进行切分
            int middle = (start + end) / 2;
            System.err.println(middle);
            //创建多个对象实现对任务的切分
            FockJoinDemo leftTask = new FockJoinDemo(start, middle);
            FockJoinDemo fightTask = new FockJoinDemo(middle + 1, end);

            //执行子任务
            leftTask.fork();
            fightTask.fork();
            //等待任务执行结束并合并及结果
            Integer join = leftTask.join();
            Integer join1 = fightTask.join();
            sum = join + join1;

        }
        return sum;
    }

    public static void main(String[] args) {
        //创建算法切分的主类
        ForkJoinPool forkJoinPool = new ForkJoinPool();

        FockJoinDemo task = new FockJoinDemo(1, 100);
        ForkJoinTask<Integer> submit = forkJoinPool.submit(task);
        try {
            log.info("result:{}", submit.get());
        } catch (Exception e) {
            log.info("excption", e);
        }
    }
}
